/**
 * Copyright (C) 2021 - 2031 O-Cubes Co., Ltd.
 */

/****************************************************************
 *  @file    spi_slave_dma_test.c
 *  @brief   SPI Slave testcase source file
 *  @version v1.0
 *  @date    03. Apr. 2023
 ****************************************************************/

#include "hal_api.h"
#include "printf.h"
#include "pcl.h"
#include "device_spi.h"
#include "common.h"

#define DMA_TX_DMA_CHAN            0
#define DMA_RX_DMA_CHAN            1
#define BUF_LEN                    64


static __align(64) uint8_t write_buf[BUF_LEN];
static __align(64) uint8_t read_buf[BUF_LEN * 4];


int32_t test_spi_slave_dma(void)
{
	uint8_t i;
	int32_t ret;

	Spi_Cfg_t spi = {DW_SPI_2_ID, 0};
	DEV_SPI_PTR spi_ptr = spi_get_dev(spi.devid);

	printf("\r\n[SPI SLAVE DMA]: TEST START\r\n");

	Hal_Pcl_FuncSet(PAD_ID_GPIO08, PAD020_FUNC_SPI2_CSN);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO08, PCL_PD_PU_ENABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO08, PCL_OUTPUT_DISABLE);

	Hal_Pcl_FuncSet(PAD_ID_GPIO09, PAD021_FUNC_SPI2_CLK);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO09, PCL_PD_PU_ENABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO09, PCL_OUTPUT_DISABLE);

	Hal_Pcl_FuncSet(PAD_ID_GPIO10, PAD022_FUNC_SPI2_SDIO);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO10, PCL_PD_PU_ENABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO10, PCL_OUTPUT_DISABLE);

	Hal_Pcl_FuncSet(PAD_ID_GPIO11, PAD023_FUNC_SPI2_SDO);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO11, PCL_PD_PU_DISABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO11, PCL_OUTPUT_ENABLE);

	spi_ptr->spi_open(DEV_SLAVE_MODE, SPI_CLK_MODE_DEFAULT);

	ret = Hal_Spi_Request_Dma_Chan(&spi, DMA_TX_DMA_CHAN, DMA_RX_DMA_CHAN);
	if(ret) {
		printf("[SPI SLAVE DMA]: requset dma chan failed\r\n");
	}
	for (i = 0; i < BUF_LEN; i++) {
		write_buf[i] = i;
	}

	spi_ptr->spi_read(write_buf, BUF_LEN, read_buf, BUF_LEN);

	Hal_Pcl_FuncSet(PAD_ID_GPIO08, PAD020_FUNC_UART4_TXD);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO08, PCL_PD_PU_DISABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO08, PCL_OUTPUT_ENABLE);

	Hal_Pcl_FuncSet(PAD_ID_GPIO09, PAD021_FUNC_UART4_RXD);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO09, PCL_PD_PU_ENABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO09, PCL_OUTPUT_DISABLE);

	Hal_Pcl_FuncSet(PAD_ID_GPIO10, PAD022_FUNC_UART4_RTS);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO10, PCL_PD_PU_DISABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO10, PCL_OUTPUT_ENABLE);

	Hal_Pcl_FuncSet(PAD_ID_GPIO11, PAD023_FUNC_UART4_CTS);
	Hal_Pcl_PdPuSet(PAD_ID_GPIO11, PCL_PD_PU_ENABLE);
	Hal_Pcl_OutputSet(PAD_ID_GPIO11, PCL_OUTPUT_DISABLE);


	printf("[SPI SLAVE]: TEST END\r\n");

	return 0;
}

